<?php 
namespace App\Http\Controllers\Setting;

use Auth;
use App\Http\Controllers\Controller;
use App\Models\Platform;
use App\Models\Role;
use App\Models\User;
use App\Models\UserPlatform;
use Illuminate\Http\Request;
use Validator;

class UserController extends Controller
{
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {

            $roles = Role::all();

            $user = $this->filters($request, new User());

            $paginator = $user->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $ups = UserPlatform::all();
            $platforms = Platform::all();

            foreach ($ups as $key => $up) {
                foreach ($platforms as $platform) {
                    if ($up->platform_id == $platform->id) {
                        $ups[$key]->name = $platform->name;
                    }
                }
            }

            $rows = [];
            foreach ($paginator as $page) {

                $platform = "";
                foreach ($ups as $key => $up) {
                    if ($up->user_id == $page->user_id) {
                        $platform .= $up->name . ",";
                    }
                }

                $rs = "";
                foreach ($roles as $role) {
                    if ($role->role_id == $page->role_id) {
                        $rs = $role->name;
                    }
                }

                $u = [];
                $u['user_id']  = $page->user_id;
                $u['name']     = $page->name;
                $u['email']    = $page->email;
                $u['platform'] = $platform;
                $u['role_id']  = $page->role_id;
                $u['desc']     = $page->desc;
                $u['avatar']   = ($page->avatar);
                $u['rs']       = $rs;
                $u['game_acc_id'] = ($page->game_acc_id);
                $rows[] = $u;
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            $rs = "";
            foreach (Role::all() as $role) {

                if ($rs) {
                        $rs .= ";";
                    }
                $rs .= "{$role->role_id}:{$role->name}";

            }

            return view('setting/user/index', ['rs' => $rs]);
        }
    }

    public function edit(Request $request)
    {
        $this->validate($request, [
            'id'          => 'required',
            'game_acc_id' => 'integer'
        ]);

        $oper = $request->get('oper');
    
        if ($oper == "del") {
            $user = User::find($request->get('id'));
            $user->delete();
            return response()->json(["success" => true]);
        }

        $user = new User();

        if ($oper == "add") {
            if (User::where("email", $request->get('email'))->first()) {
                return response()->json(["success" => false , "message" => "用户名已存在"]);
            }

            $user->password = bcrypt('123456');

        } else if ($oper == "edit") {
    
            $user = User::find($request->get('id'));
            if (!$user) {
                return response()->json(["success" => false , "message" => "参数错误"]);
            }
        }

        $user->name        = $request->get('name');
        $user->email       = $request->get('email');
        $user->role_id     = $request->get('role_id');
        $user->desc        = $request->get('desc');
        $user->game_acc_id = $request->get('game_acc_id');
        $user->save();

        return response()->json(["success" => true]);
    }

    public function avatar(Request $request)
    {
        $this->validate($request, [
            'avatar' => 'required',
        ]);

        $avatar = $request->get("avatar");

        $meta = stream_get_meta_data(fopen($avatar, 'r'));
        if ($meta['mediatype'] != "image/png") {
            return redirect()->back()->withErrors("图片格式错误");
        }

        $user = Auth::user();
        $user->avatar = $avatar;
        $user->save();

        return redirect()->back()->withInput(['上传成功']);
    }
}